package com.gitee.wsl.coroutines

import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.CoroutineName
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.SupervisorJob

interface CoroutineScopeOwner {
     val coroutineScope: CoroutineScope

     companion object {
         fun create(
            coroutineScope: CoroutineScope,
        ): CoroutineScopeOwner =
            object : CoroutineScopeOwner {
                override val coroutineScope: CoroutineScope
                    get() = coroutineScope
            }
    }
}

 fun CoroutineScope.createChildCoroutineScope(name: String): CoroutineScope =
    CoroutineScope(
        context = SupervisorJob(coroutineContext[Job]) +
                CoroutineName("Child: $name") +
                ComponentalDispatchers.contextCoroutineDispatcher
    )

 object ComponentalDispatchers {

     val optimalMain: CoroutineDispatcher by lazy {
        try {
            Dispatchers.Main.immediate
        } catch (e: UnsupportedOperationException) {
            Dispatchers.Main
        }
    }

     val contextCoroutineDispatcher: CoroutineDispatcher
        get() = Dispatchers.Default
}